<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="业务员" prop="smName">
        <el-input
            v-model="queryParams.smName"
            placeholder="请输入业务员"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactPhone">
        <el-input
            v-model="queryParams.contactPhone"
            placeholder="请输入联系方式"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入账号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="经销商" prop="parName" v-if="userStore.userType === '0'">
        <el-input
            v-model="queryParams.parName"
            placeholder="请输入经销商"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:tsm:add']"
            :class="{'but-disabled': userStore.isRead === 1}"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:tsm:remove']"
            :class="{'but-disabled': userStore.isRead === 1}"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:tsm:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tsmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="业务员" align="center" prop="smName"/>
      <el-table-column label="经销商" align="center" prop="parName" v-if="userStore.userType === '0'"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="联系方式" align="center" prop="contactPhone"/>
      <el-table-column label="联系地址" align="center" prop="contactAddr"/>
      <el-table-column label="账号" align="center" prop="userName"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)"
                     v-hasPermi="['system:tsm:query']">查看
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1}"
                     v-hasPermi="['system:tsm:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     :class="{'but-disabled': userStore.isRead === 1}"
                     v-hasPermi="['system:tsm:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改业务员对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tsmRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="userStore.userType === '0'">
            <el-form-item label="经销商" prop="parId">
              <par-select :key="refreshTime" v-model="form.parId"></par-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员" prop="smName">
              <el-input v-model="form.smName" placeholder="请输入业务员" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系方式"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="contactAddr">
              <el-input v-model="form.contactAddr" type="textarea" placeholder="请输入联系地址" maxlength="200"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="userName">
              <el-input v-model="form.userName" @blur="changeUserName" placeholder="请输入账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-if="!form.smId > 0">
              <el-input v-model="form.password" type="password" show-password autocomplete="off"
                        placeholder="请输入密码"/>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword" v-if="form.smId > 0">
              <el-input v-model="form.newPassword" type="password" show-password autocomplete="off"
                        placeholder="请输入新密码"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="业务员详情" v-model="viewOpen" width="500px" append-to-body>
      <el-form ref="tsmRefView" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="userStore.userType === '0'">
            <el-form-item label="经销商" prop="parId">
              {{ form.parName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员" prop="smName">
              {{ form.smName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactPhone">
              {{ form.contactPhone }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <dict-tag :options="sys_user_sex" :value="form.sex"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="contactAddr">
              {{ form.contactAddr }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号" prop="userName">
              {{ form.userName }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Tsm">
import {listTsm, getTsm, delTsm, addTsm, updateTsm} from "@/api/system/tsm";
import ParSelect from "@/components/ParSelect/index.vue";
import {ref} from "vue";
import useUserStore from "@/store/modules/user";

const userStore = useUserStore()
const {proxy} = getCurrentInstance();
const {sys_user_sex} = proxy.useDict("sys_user_sex");

const tsmList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const refreshTime = ref(0);
const viewOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    smName: undefined,
    smDesc: undefined,
    sex: undefined,
    contactPhone: undefined,
    contactAddr: undefined,
    userName: undefined,
    password: undefined,
    parId: undefined,
  },
  rules: {
    parId: [
      {required: true, message: "经销商不能为空", trigger: "change"}
    ],
    smName: [
      {required: true, message: "业务员不能为空", trigger: "blur"}
    ],
    contactPhone: [
      {required: true, message: "联系方式不能为空", trigger: "blur"}
      , {pattern: /^(1[3|4|5|6|7|8|9]\d{9})$|^(\d{3,4}-\d{7,8})$/, message: "请输入正确的手机号码", trigger: "blur"}
    ],
    sex: [{required: true, message: "性别不能为空", trigger: "blur"}],
    userName: [{
      required: true, message: "账号不能为空", trigger: "blur"
    }, {pattern: /^(1[3|4|5|6|7|8|9]\d{9})$|^(\d{3,4}-\d{7,8})$/, message: "请输入正确的手机号码", trigger: "blur"}],
    password: [{required: true, message: "密码不能为空", trigger: "blur"}, {
      pattern: /^[A-Za-z0-9]+$/,
      message: "密码只能包含英文字母和数字",
      trigger: "blur"
    }, {
      min: 8,
      max: 30,
      message: "密码长度必须介于 8 和 30 之间",
      trigger: "blur"
    }],
    newPassword: [{
      pattern: /^[A-Za-z0-9]+$/,
      message: "密码只能包含英文字母和数字",
      trigger: "blur"
    }, {
      min: 8,
      max: 30,
      message: "密码长度必须介于 8 和 30 之间",
      trigger: "blur"
    }],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询业务员列表 */
function getList() {
  loading.value = true;
  listTsm(queryParams.value).then(response => {
    tsmList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    smId: undefined,
    smName: undefined,
    smDesc: undefined,
    sex: '1',
    contactPhone: undefined,
    contactAddr: undefined,
    userName: undefined,
    password: undefined,
    parId: undefined,
    ext1: undefined,
    ext2: undefined,
    ext3: undefined,
    state: undefined,
    createTime: undefined,
    creator: undefined,
    modifyTime: undefined,
    modifier: undefined
  };
  proxy.resetForm("tsmRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.smId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  refreshTime.value += 1
  open.value = true;
  title.value = "添加业务员";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _smId = row.smId || ids.value
  getTsm(_smId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改业务员";
    refreshTime.value += 1
  });
}

function handleView(row) {
  const _smId = row.smId || ids.value
  getTsm(_smId).then(response => {
    form.value = response.data;
    viewOpen.value = true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tsmRef"].validate(valid => {
    if (valid) {
      if (form.value.smId != null) {
        updateTsm(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTsm(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _smIds = row.smId || ids.value;
  proxy.$modal.confirm('是否确认删除业务员编号为"' + _smIds + '"的数据项？').then(function () {
    return delTsm(_smIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/tsm/export', {
    ...queryParams.value
  }, `tsm_${new Date().getTime()}.xlsx`)
}

function changeUserName() {
  if (form._object.form.userName != '' && form._object.form.userName.length == 11 && (form._object.form.password == undefined || form._object.form.password.length == 0)) {
    form._object.form.password = form._object.form.userName.slice(-4) + 'touy'
  }
}


onActivated(() => {
  getList();
})
getList();
</script>
